<?php

namespace app\model;

use Exception;
use think\Model;

class ActionBaseModel extends Model
{

    /**
     * 根据id获取一条信息
     *
     * @param integer $intId
     * @return array
     */
    public static function getOneById(int $intId): array
    {
        $objModel = self::find($intId)->hide(['admin_pwd']);
        if (empty($objModel)) {
            return [];
        }

        return $objModel->toArray();
    }

    /**
     * 根据where条件获取一条信息
     *
     * @param array $arrWhere 
     * @return array
     */
    public static function getOneByWhere(array $arrWhere): array
    {
        $objModel = self::where($arrWhere)->find();
        if (empty($objModel)) {
            return [];
        }

        return $objModel->toArray();
    }

    /**
     * 根据 where 条件，更新一条信息
     *
     * @param array $arrWhere
     * @param array $arrUpdateData
     * @return void
     */
    public static function updateOneByWhere(array $arrWhere, array $arrUpdateData): void
    {
        $objModel = self::where($arrWhere)->find();
        if (empty($objModel)) {
            throw new Exception('数据不存在');
        }
        self::where($arrWhere)->update($arrUpdateData);
    }

    /**
     * 全量查询(不分页)
     */
    public static function getAllList(
        array $arrWhere,
        array $arrField = ['*'],
        string $strOrder = 'id',
        string $strSort = 'desc'
    ): array {
        return self::where($arrWhere)
            ->order($strOrder, $strSort)
            ->field($arrField)
            ->select()
            ->toArray();
    }


    /**
     * 查询总数量，配合分页查询
     *
     * @param array $arrWhere
     * @return integer
     */
    public static function getAllCount(array $arrWhere = []): int
    {
        return self::where($arrWhere)->count();
    }
    /**
     * 分页查询
     *
     * @param integer $intPageIndex
     * @param integer $intPageSize
     * @param array $arrWhere
     * @param array $arrField
     * @param string $strOrder
     * @param string $strSort
     * @return array
     */
    public static function getPageList(
        int $intPageIndex = 1,
        int $intPageSize = 10,
        array $arrWhere = [],
        array $arrField = ['*'],
        string $strOrder = 'id',
        string $strSort = 'desc'
    ): array {
        return self::where($arrWhere)
            ->order($strOrder, $strSort)
            ->field($arrField)
            ->page($intPageIndex, $intPageSize)
            ->select()
            ->toArray();
    }

    /**
     * 插入一条记录，返回新生成的id
     * @param array $arrInsertData
     * @return int
     */
    public function insertOne(array $arrInsertData): int
    {
        return $this->insert($arrInsertData, true);
    }
}
